import os
import sys
import shutil
import platform

# prepare the project
os.chdir("..")
os.system("git pull")

OS_PLATFORM = platform.system()
PYTHON_VERSION = sys.version
if PYTHON_VERSION[0] != "3":
    print("\033[31m[WARN] 启动失败，本项目仅支持python3，请使用指定版本运行！\033[0m")
    print(f"\033[31m[WARN] 你的python版本为: {PYTHON_VERSION}\033[0m")
    sys.exit()

# Build settings
MAIN_FILE = "main.py"
# General settings(can be "")
BIN_NAME = "DLS"
BIN_PATH = "bin"
ICON_PATH = "assets/logo.ico"
BUILD_ONLY_ONE_FILE = True

if OS_PLATFORM != 'Windows':
    BIN_NAME = "dls"

# Install dependence settings(can be "")
INSTALL_MIRROR_URL = "https://pypi.tuna.tsinghua.edu.cn/simple"

# Create install command
PYTHON_PATH = sys.executable
USE_PIP = f"{PYTHON_PATH} -m pip install"
if INSTALL_MIRROR_URL:
    USE_PIP += f" -i {INSTALL_MIRROR_URL}"


def install(package: str) -> None:
    command = USE_PIP
    if package == "requirements.txt":
        command += f" -r {package}"
    else:
        command += f" {package}"
    print(command)
    os.system(command)


# Create build command
BUILD_CMD = f"pyinstaller {MAIN_FILE}"
if BUILD_ONLY_ONE_FILE:
    BUILD_CMD += " -F"
if BIN_NAME:
    BUILD_CMD += f" -n {BIN_NAME}"
if ICON_PATH:
    BUILD_CMD += f" -i {ICON_PATH}"
if BIN_PATH:
    BUILD_CMD += f" --distpath {BIN_PATH}"


# pack full winpty
def pack_lib(cmd: str):
    if OS_PLATFORM == 'Windows':
        import inspect
        import winpty
        lib_path = os.path.split(inspect.getfile(winpty))[0]
        agent_path = os.path.join(lib_path, "winpty-agent.exe")
        cmd += f' --add-data="{agent_path};winpty/"'
    return cmd


def build() -> None:
    os.system(pack_lib(BUILD_CMD))


def clean():
    """
    clear all bin files
    warn: ensure there's no important files in BIN_PATH
    """
    if BIN_PATH and os.path.exists(BIN_PATH) and os.path.isdir(BIN_PATH):
        shutil.rmtree(BIN_PATH)


if __name__ == '__main__':
    print("\033[32m[INFO][1/3] 安装依赖...\033[0m")
    install("pyinstaller")
    install("requirements.txt")
    print("\033[32m[INFO][2/3] 清理目录...\033[0m")
    clean()
    print("\033[32m[INFO][3/3] 编译程序...\033[0m")
    build()
    print("\033[32m[INFO] 构建已完成！\033[0m")

# Create requirements.txt: pipreqs ./ --encoding=utf8
# pyinstaller -F main.py -n "DLS" -i "img/logo.ico" --distpath "bin"
